package com.flydog.taskManager.common.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 全局异常处理类
 *
 * @author caoweidong
 * @version 0.0.0
 * @create 2021/6/28 10:35
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = ApiException.class)
    public CommonResult<Object> apiExceptionHandler(HttpServletRequest req, ApiException e) {
        return CommonResult.failed(e.getErrorCode(), e.getErrorMsg());
    }
    @ExceptionHandler(value = BindException.class)
    public CommonResult<Object> validateExceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();

        return CommonResult.validateFailed(getErrors(bindingResult));
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public CommonResult<Object> validateExceptionHandler(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        return CommonResult.validateFailed(getErrors(constraintViolations));
    }

    private Map<String, Object> getErrors(BindingResult result) {
        Map<String, Object> map = new HashMap<>();
        List<FieldError> list = result.getFieldErrors();
        for (FieldError error : list) {
            map.put(error.getField(), error.getDefaultMessage());
        }
        return map;
    }

    private Map<String, Object> getErrors(Set<ConstraintViolation<?>> constraintViolations) {
        Map<String, Object> map = new HashMap<>();
        for (ConstraintViolation<?> violation : constraintViolations) {
            map.put(violation.getPropertyPath().toString(), violation.getMessage());
        }
        return map;
    }
}

